<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, resetTemplate } from './autoCode.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    getFlowSequenceEditPage,
    getFlowSequenceCreate,
    getFlowSequenceUpdate,
  } from '/@/api/flowManage/flowManage';
  export default defineComponent({
    name: 'AutoCodeDrawer',
    components: {
      BasicDrawer,
      BasicForm,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let dataRef = ref({});

      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      let oaNoticeAttList = ref([]);
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = data?.isUpdate;
        oaNoticeAttList.value = [];
        if (unref(isUpdate)) {
          const res = await getFlowSequenceEditPage({ id: data.record.id });
          dataRef.value = {
            ...res,
          };
          setFieldsValue({
            ...unref(dataRef),
          });
        } else {
          dataRef.value = {
            curIndex: 0,
            curValue: '',
            template: '{num}',
            yearNumReset: '{num}',
            yearNum: '',
            length: 0,
            itemSeparator: '',
            yearDigit: '4',
            beginIndex: 1,
          };
          setFieldsValue({
            ...unref(dataRef),
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          console.log('dataRef111', unref(dataRef));
          const values = await validate();
          let formData = Object.assign({}, unref(dataRef), values);

          console.log('formData', formData);
          setDrawerProps({ confirmLoading: true });
          if (!unref(isUpdate)) {
            await getFlowSequenceCreate(formData);
          } else {
            await getFlowSequenceUpdate(formData);
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
